/**
 * 背包数据
 * @swyan 
 *
 */
class Bags {
    private static _instance: Bags;
    private static _allowInstance: Boolean;
    private _allItems: Object;
    public constructor() {
        if(!Bags._allowInstance)
            return;

        GameBus.getInstance().addEventListener(SocketEvent.ReceiveProtocol,this.receive,this);
    }

    public static getInstance(): Bags {
        if(this._instance == null) {
            this._allowInstance = true;
            this._instance = new Bags();
            this._allowInstance = false;
        }
        return this._instance;
    }
    
    /**接收协议**/
    private receive(event: egret.Event): void {
        var data: Object;
        if(event.data == Protocol.BACKPACK) {//背包数据
            //角色数据协议
            data = ProtocolInfo.getInstance().getProtocol(Protocol.BACKPACK);
            if(data) {
                this.setItems(data["items"]);
            }
        }
    }

    private setItems(arr: Object[]): void {
        if(arr == null)
            return;
        this._allItems = new Object();
        var data: ItemData;
        for(var i: number = 0;i < arr.length;i++) {
            data = new ItemData();
            data.id = arr[i]["id"];
            data.type = arr[i]["type"];
            data.lev = arr[i]["lev"];
            data.num = arr[i]["num"];
            if(this._allItems.propertyIsEnumerable(data.type.toString()) == false)
                this._allItems[data.type] = new Object();
            this._allItems[data.type][data.id] = data;
        }
        GameBus.getInstance().dispatchEvent(new ItemEvent(ItemEvent.Init));
    }

    public getItemsByType(type: number): Object {
        return this._allItems[type];
    }
}
